<?php

namespace App\Repositories;

use App\Models\Setting;

class SettingRepository
{

    /**
     * 根据名称获取配置
     *
     * @param string $name
     * @return mixed
     */
    public function getByName($name)
    {
        return Setting::where('name', $name)->first();
    }

    /**
     * 根据ID获取配置
     *
     * @param int $id
     * @return mixed
     */
    public function getById($id)
    {
        return Setting::find($id);
    }

    /**
     * 创建配置
     *
     * @param array $attributes
     * @return $this|\Illuminate\Database\Eloquent\Model
     */
    public function create(array $attributes)
    {
        $user = Setting::create($attributes);
        return $user;
    }

    /**
     * 修改配置
     *
     * @param array $attributes
     * @param Setting $setting
     * @return bool
     */
    public function update(array $attributes, Setting $setting)
    {
        return $setting->update($attributes);
    }

    /**
     * 删除配置
     *
     * @param Setting $setting
     * @throws \Exception
     */
    public function destroy(Setting $setting)
    {
        $setting->delete();
    }

    /**
     * 获取配置分页列表
     *
     * @param array $condition
     * @param int $per_page
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function paginate($condition = [], $per_page = 20)
    {
        $setting = Setting::orderBy('sort', 'asc')->orderBy('id', 'asc');
        if (isset($condition['group']) && is_numeric($condition['group']) && $condition['group'] > 0) {
            $setting->where('group', $condition['group']);
        }
        if (isset($condition['name'])) {
            $setting->where('name', $condition['name']);
        }
        if (isset($condition['title'])) {
            $setting->where('title', 'like', '%' . $condition['title'] . '%');
        }
        return $setting->paginate($per_page);
    }

    /**
     * 获取指定组的所有配置
     *
     * @param int $group
     * @return mixed
     */
    public function getByGroup($group)
    {
        return Setting::where('group', $group)->orderBy('sort', 'asc')->orderBy('id', 'asc')->get();
    }

    /**
     * 取得所有配置
     *
     * @return mixed
     */
    public function all()
    {
        return Setting::orderBy('sort', 'asc')->orderBy('id', 'asc')->get();
    }
}
